//
//  M4PositiveReviewsAlertVIew.swift
//  M4
//
//  Created by YuChuang on 2024/8/22.
//

import UIKit
import StoreKit

class M4PositiveReviewsAlertVIew: UIView {
    
    @IBOutlet weak var M4PRSuccessView: UIView!
    
    @IBOutlet weak var M4PRSuccessViewHeight: NSLayoutConstraint!//34
    
    @IBOutlet weak var M4PRSuccessViewBotttom: NSLayoutConstraint!//20
    
    @IBOutlet weak var M4PRStackView: UIStackView!
    
    private var ratingButtons = [UIButton]()
    
    private var currentRating = 0 {
        didSet {
            updateButtonSelectionStates()
        }
    }
    
    override func awakeFromNib() {
        self.frame = CGRect(x: 0, y: 0, width: M4ScreenWidth, height: M4ScreenHeight)
        M4PRSuccessView.isHidden = true
        M4PRSuccessViewHeight.constant = 0
        M4PRSuccessViewBotttom.constant = 0
        M4PRStackView.distribution = .equalSpacing
        M4PRStackView.translatesAutoresizingMaskIntoConstraints = false
        M4PRStackView.axis = .horizontal
        createRatingButtons()
        layoutRatingButtons()
    }
    
    @IBAction func M4PRSubmitButton(_ sender: UIButton) {
        if currentRating == 0 {
            self.M4AlertViewHidden()
            if M4BaseViewController.M4CurrentVC()?.navigationController?.viewControllers.first is M4FirstInfoViewController {
                AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
            }
            else {
                M4BaseViewController.M4CurrentVC()?.navigationController?.popToRootViewController(animated: true)
            }
        }
        else {
            let para: [String : Any] = ["PEQw": "ESP", "nsdWe": M4UserDataManager.m4UserShare.M4Token, "mwEEeq": M4UserDataManager.m4UserShare.M4Itemcode, "wiPOe": currentRating]
            M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4SubmitStat, .post, params: para)) { model in
                sender.M4EventUnavailable = false
                if model.code == 1 {
                    self.M4PRSuccessView.isHidden = false
                    self.M4PRSuccessViewHeight.constant = 34
                    self.M4PRSuccessViewBotttom.constant = 20
                    DispatchQueue.main.asyncAfter(deadline: .now()+2.0) {
                        self.M4AlertViewHidden()
                        if self.currentRating >= 5 {
                            if #available(iOS 14.0, *) {
                                guard let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else { return }
                                SKStoreReviewController.requestReview(in: scene)
                            } else {
                                // Fallback on earlier versions
                                SKStoreReviewController.requestReview()
                            }
                        }
                    }
                }
                else {
                    self.M4AlertViewHidden()
                }
            }
        }
    }
    
    @IBAction func M4PRCloseAction(_ sender: UIButton) {
        self.M4AlertViewHidden()
        sender.M4EventUnavailable = false
    }
    
    private func createRatingButtons() {
        for _ in 1...5 {
            let button = UIButton()
            button.setImage(UIImage(named: "icon_star_nor"), for: .normal)
            button.setImage(UIImage(named: "icon_star_pre"), for: .selected)
            button.adjustsImageWhenHighlighted = false
            button.addTarget(self, action: #selector(ratingButtonTapped(button:)), for: .touchUpInside)
            ratingButtons.append(button)
        }
    }
    
    private func layoutRatingButtons() {
        ratingButtons.forEach { button in
            M4PRStackView.addArrangedSubview(button)
            button.widthAnchor.constraint(equalToConstant: 40).isActive = true
            button.heightAnchor.constraint(equalToConstant: 41).isActive = true
        }
    }
    
    @objc private func ratingButtonTapped(button: UIButton) {
        guard let index = ratingButtons.firstIndex(of: button) else { return }
        
        let selectedRating = index + 1
        if selectedRating > currentRating {
            for i in currentRating..<selectedRating {
                ratingButtons[i].isSelected = true
            }
        } else {
            for i in selectedRating..<currentRating {
                ratingButtons[i].isSelected = false
            }
        }
        
        currentRating = selectedRating
        button.M4EventUnavailable = false
    }
    
    private func updateButtonSelectionStates() {
        for (index, button) in ratingButtons.enumerated() {
            button.isSelected = index < currentRating
        }
    }
    
    
}
